package com.youlai.boot.modules.game.controller;


import com.youlai.boot.modules.game.service.OssService;
import com.youlai.boot.common.result.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.core.io.buffer.DataBufferLimitException;


@RestController
@RequestMapping("/api/v1/game-files")
@Tag(name = "游戏文件上传", description = "游戏相关文件上传接口")
@RequiredArgsConstructor
@CrossOrigin(origins = {"http://localhost:3000", "http://localhost:3002"}, allowedHeaders = "*", maxAge = 3600)
@Slf4j
public class GameFileController {

    private final OssService ossService;

    @PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @Operation(summary = "游戏文件上传", description = "上传游戏相关文件到服务器")
    public Result<String> uploadFile(
            @RequestParam(value = "file") MultipartFile file
    ) {
        log.info("接收到文件上传请求: 文件名={}, 大小={}KB, 类型={}", 
                 file != null ? file.getOriginalFilename() : "null", 
                 file != null ? file.getSize() / 1024 : 0,
                 file != null ? file.getContentType() : "unknown");
        
        try {
            if (file == null || file.isEmpty()) {
                log.warn("上传的文件为空");
                return Result.failed("请选择要上传的文件");
            }
            
            // 检查文件类型（仅允许图片格式）
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                log.warn("上传的文件类型不支持: {}", contentType);
                return Result.failed("只支持上传图片文件");
            }
            
            // 检查文件大小 - 配置了spring.servlet.multipart.max-file-size=10MB
            // 这里是二次检查，超大文件会被Spring框架拦截
            if (file.getSize() > 8 * 1024 * 1024) { // 8MB
                log.warn("上传的文件大小超过限制: {}KB", file.getSize() / 1024);
                return Result.failed("文件大小不能超过8MB");
            }
            
            String fileInfo = ossService.uploadFileAvatar(file);
            
            if (fileInfo == null) {
                log.error("文件上传到OSS失败");
                return Result.failed("文件上传失败，请稍后重试");
            }
            
            log.info("文件上传成功: {}", fileInfo);
            return Result.success(fileInfo);
        } catch (MaxUploadSizeExceededException e) {
            log.error("文件大小超出限制:", e);
            return Result.failed("文件大小超出限制，最大支持10MB");
        } catch (DataBufferLimitException e) {
            log.error("文件缓冲区大小超出限制:", e);
            return Result.failed("文件大小超出限制，最大支持10MB");
        } catch (Exception e) {
            log.error("文件上传处理异常", e);
            return Result.failed("文件上传异常: " + e.getMessage());
        }
    }

    @DeleteMapping
    @Operation(summary = "删除游戏文件", description = "从服务器删除指定游戏文件")
    public Result<Boolean> deleteFile(
             @RequestParam String filePath
    ) {
        log.info("接收到文件删除请求: filePath={}", filePath);
        
        try {
            if (filePath == null || filePath.isEmpty()) {
                log.warn("文件路径为空");
                return Result.failed("文件路径不能为空");
            }
            
            boolean result = ossService.deleteFile(filePath);
            
            if (!result) {
                log.error("文件删除失败: {}", filePath);
                return Result.failed("文件删除失败，请稍后重试");
            }
            
            log.info("文件删除成功: {}", filePath);
            return Result.success(result);
        } catch (Exception e) {
            log.error("文件删除处理异常", e);
            return Result.failed("文件删除异常: " + e.getMessage());
        }
    }
}
